package com.molyfun.parents.fragment.main;

import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.text.format.Time;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.ChooseDateActivity;
import com.molyfun.parents.activity.course.view.CourseView;
import com.molyfun.parents.activity.coursecenter.DayCourseListActivity;
import com.molyfun.parents.activity.report.ReportDetailActivity;
import com.molyfun.parents.activity.report.ReportResultActivity;
import com.molyfun.parents.activity.report.plan.PlanDetailActivity;
import com.molyfun.parents.activity.schoolonline.homework.DayHomeworkListActivity;
import com.molyfun.parents.activity.schoolonline.homework.view.DateChooseView;
import com.molyfun.parents.activity.schoolonline.homework.view.HomeWorkView;
import com.molyfun.parents.activity.setting.MineActivity;
import com.molyfun.parents.fragment.BaseFragment;
import com.molyfun.parents.fragment.dialog.CommonDialogFragment;
import com.molyfun.parents.rest.bean.CourseListResponse;
import com.molyfun.parents.rest.bean.HomeWorkResponse;
import com.molyfun.parents.rest.bean.SchoolliveAllResponse;
import com.molyfun.parents.uievent.EventDispatcherEnum;
import com.molyfun.parents.uievent.UIEventListener;
import com.molyfun.parents.utils.Const;
import com.molyfun.parents.utils.TimeUtils;
import com.molyfun.parents.view.HorizontalTagBar;
import com.molyfun.parents.view.calendar.DayView;
import com.molyfun.parents.view.calendar.MaterialCalendarView;
import com.molyfun.parents.view.swipeRefreshLayout.SwipeRefreshLayout;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.carbs.android.expandabletextview.library.ExpandableTextView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by ZhaoWei on 2016/12/5.
 * 首页
 */

public class SchoolOnlineFragment extends BaseFragment implements View.OnClickListener, UIEventListener, SwipeRefreshLayout.OnRefreshListener, SwipeRefreshLayout.OnLoadListener {

    private String mCurrentDate = TimeUtils.getQueryDate();

    @InjectView(R.id.date_choose_layout)
    DateChooseView mDateChooseView;
    @InjectView(R.id.today_summery_layout)
    LinearLayout mSummeryLayout;
    @InjectView(R.id.summery_text)
    ExpandableTextView mSummeryText;

    @InjectView(R.id.course_layout)
    LinearLayout mCourseLayout;
    @InjectView(R.id.course_list_layout)
    LinearLayout mCourseListLayout;

    @InjectView(R.id.homeworklayout)
    LinearLayout mHomeWorkLayout;
    @InjectView(R.id.homework_list_layout)
    LinearLayout mHomeworkListLayout;

    @InjectView(R.id.evaluate_layout)
    LinearLayout mEvaluateLayout;
    @InjectView(R.id.evaluate_layout_tag)
    HorizontalTagBar mEvaluateHorizontalTagBar;
    @InjectView(R.id.plan_layout)
    LinearLayout mPlanLayout;
    @InjectView(R.id.plan_layout_tag)
    HorizontalTagBar mPlanHorizontalTagBar;
    @InjectView(R.id.report_layout)
    LinearLayout mReportLayout;
    @InjectView(R.id.report_layout_tag)
    HorizontalTagBar mReportHorizontalTagBar;
    @InjectView(R.id.no_data_layout)
    TextView mNoDataLayout;
    @InjectView(R.id.container_layout)
    LinearLayout mContainerLayout;
    @InjectView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    @InjectView(R.id.profile_icon)
    ImageView mProfileIcon;

    Time today = new Time(Time.getCurrentTimezone());

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_school_online, container, false);
        ButterKnife.inject(this, view);
        getSchoolLive(TimeUtils.getQueryDate());

        mDateChooseView.setDateChooseViewCallback(new DateChooseView.DateChooseViewCallback() {
            @Override
            public void onDayPreClick() {
                changeDate(TimeUtils.getPreDate(mCurrentDate));
            }

            @Override
            public void onDateClick() {
//                new DateChooseDialogFragment.DateChooseDialogBuilder(mCurrentDate, MaterialCalendarView.PageIdentify.PageCourse)
//                        .setChooseCallBack(SchoolOnlineFragment.this)
//                        .build(getChildFragmentManager().beginTransaction());
                ChooseDateActivity.startActivity(getContext(), mCurrentDate, MaterialCalendarView.PageIdentify.PageCourse);
            }

            @Override
            public void onDayNextClick() {
                changeDate(TimeUtils.getNextDate(mCurrentDate));
            }
        });
        String todayDate = TimeUtils.getQueryDate();
        mDateChooseView.setDate(todayDate);

        mCourseLayout.setOnClickListener(this);
        mHomeWorkLayout.setOnClickListener(this);

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setOnLoadListener(this);
        mSwipeRefreshLayout.setTopColor(R.color.refresh_color_01, R.color.refresh_color_02,
                R.color.refresh_color_02, R.color.refresh_color_01);
        mSwipeRefreshLayout.setBottomColor(R.color.color_transparent, R.color.color_transparent,
                R.color.color_transparent, R.color.color_transparent);
        mSwipeRefreshLayout.setMode(SwipeRefreshLayout.Mode.BOTH);
        mSwipeRefreshLayout.setLoadNoFull(true);
        mProfileIcon.setOnClickListener(this);

        MFPApplication.getInstance().getEventController().addUIEventListener(EventDispatcherEnum.UI_EVENT_DATE_CHANGE, this);


        return view;
    }

    @Override
    public void onRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
        mSwipeRefreshLayout.setLoading(false);
        getSchoolLive(mCurrentDate);
    }


    @Override
    public void onLoad() {
        mSwipeRefreshLayout.setRefreshing(false);
        mSwipeRefreshLayout.setLoading(false);
    }

    private void changeDate(String date) {

        if (!compareToday(date)) {
            new CommonDialogFragment.CommonDialogBuilder("不能选择今日之后日期的课程")
                    .build(getChildFragmentManager().beginTransaction());
            return;
        }
        if (DayView.sDayViewHasDataMap.containsKey(date) && !DayView.sDayViewHasDataMap.get(date)) {
            new CommonDialogFragment.CommonDialogBuilder("当前日期没有课程")
                    .build(getChildFragmentManager().beginTransaction());
            //TODO 刷新数据
            mCurrentDate = date;
            mDateChooseView.setDate(date);
            getSchoolLive(date);
            Const.CURRENT_COURSE_DAY_STR = date;
            return;
        }
        if (!TextUtils.isEmpty(date)) {
            mCurrentDate = date;
            mDateChooseView.setDate(date);
            getSchoolLive(date);
            Const.CURRENT_COURSE_DAY_STR = date;
        }
    }

    //时间是否小于等于今天
    private boolean compareToday(String time1) {
        today.setToNow();
        String[] times1 = time1.split("-");
        return (Integer.parseInt(times1[0]) < today.year) ||
                ((Integer.parseInt(times1[0]) == today.year) && (Integer.parseInt(times1[1]) < (today.month + 1))) ||
                ((Integer.parseInt(times1[1]) == (today.month + 1)) && (Integer.parseInt(times1[2]) <= today.monthDay));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.course_layout:
                DayCourseListActivity.startActivity(getContext(), mCurrentDate);
                break;
            case R.id.homeworklayout:
                DayHomeworkListActivity.startActivity(getContext(), mCurrentDate);
                break;
            case R.id.profile_icon:
                MineActivity.startActivity(getContext());
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        MFPApplication.getInstance().getEventController().removeUIEventListener(EventDispatcherEnum.UI_EVENT_DATE_CHANGE, this);
    }


    private void getSchoolLive(String plandatetimestr) {
        Call<SchoolliveAllResponse> call = MFPApplication.getInstance().getRestClient().getSchoolLive(plandatetimestr);
        call.enqueue(new Callback<SchoolliveAllResponse>() {
            @Override
            public void onResponse(Call<SchoolliveAllResponse> call, Response<SchoolliveAllResponse> response) {
                if (response.body() != null) {
                    if (response.body().getCode() == 200) {
                        if (response.body().getData() != null) {
                            mNoDataLayout.setVisibility(View.GONE);
                            mContainerLayout.setVisibility(View.VISIBLE);
                            SchoolliveAllResponse.SchoolLiveAllBean schoolLiveAllBean = response.body().getData();

                            if ((schoolLiveAllBean.getSummerypage() == null || TextUtils.isEmpty(schoolLiveAllBean.getSummerypage().getCoursesummarycontent())) &&
                                    (schoolLiveAllBean.getCoursesummarypage() == null || schoolLiveAllBean.getCoursesummarypage().size() == 0) &&
                                    (schoolLiveAllBean.getTaskpage() == null || schoolLiveAllBean.getTaskpage().size() == 0) &&
                                    (schoolLiveAllBean.getTrainingreportevaluatepage() == null || ((schoolLiveAllBean.getTrainingreportevaluatepage().getEvaluatelist() == null || schoolLiveAllBean.getTrainingreportevaluatepage().getEvaluatelist().size() == 0)
                                            && (schoolLiveAllBean.getTrainingreportevaluatepage().getReportlist() == null || schoolLiveAllBean.getTrainingreportevaluatepage().getReportlist().size() == 0)
                                            && (schoolLiveAllBean.getTrainingreportevaluatepage().getTraininglist() == null || schoolLiveAllBean.getTrainingreportevaluatepage().getTraininglist().size() == 0)))) {


                                mNoDataLayout.setVisibility(View.VISIBLE);
                                mContainerLayout.setVisibility(View.GONE);
                                return;
                            }

                            if (schoolLiveAllBean.getSummerypage() != null && !TextUtils.isEmpty(schoolLiveAllBean.getSummerypage().getCoursesummarycontent())) {
                                mSummeryLayout.setVisibility(View.VISIBLE);
                                mSummeryText.setText(schoolLiveAllBean.getSummerypage().getCoursesummarycontent());
                            } else {
                                mSummeryLayout.setVisibility(View.GONE);

                            }

                            //课程列表
                            if (schoolLiveAllBean.getCoursesummarypage() != null && schoolLiveAllBean.getCoursesummarypage().size() > 0) {
                                mCourseLayout.setVisibility(View.VISIBLE);
                                mCourseListLayout.removeAllViews();
                                int count = 0;
                                for (CourseListResponse.CourseBean courseBean : schoolLiveAllBean.getCoursesummarypage()) {
                                    CourseView courseView = new CourseView(getContext());
                                    courseView.initData(courseBean, null, count == (schoolLiveAllBean.getCoursesummarypage().size() - 1));
                                    mCourseListLayout.addView(courseView);
                                    count++;
                                    if (count >= 2) {
                                        break;
                                    }
                                }
                            } else {
                                mCourseLayout.setVisibility(View.GONE);
                            }

                            //作业列表
                            if (schoolLiveAllBean.getTaskpage() != null && schoolLiveAllBean.getTaskpage().size() > 0) {
                                mHomeWorkLayout.setVisibility(View.VISIBLE);
                                mHomeworkListLayout.removeAllViews();
                                int position = 0;
                                for (HomeWorkResponse.HomeWorkBean homeWorkBean : schoolLiveAllBean.getTaskpage()) {
                                    HomeWorkView homeWorkView = new HomeWorkView(getContext());
                                    if (position == (schoolLiveAllBean.getTaskpage().size() - 1)) {
                                        homeWorkView.initData(homeWorkBean, true);
                                    } else {
                                        homeWorkView.initData(homeWorkBean);
                                    }
                                    mHomeworkListLayout.addView(homeWorkView);
                                    position++;
                                }
                            } else {
                                mHomeWorkLayout.setVisibility(View.GONE);
                            }

                            if (schoolLiveAllBean.getTrainingreportevaluatepage() != null) {
                                final SchoolliveAllResponse.TrainingReportEvaluatePage trainingReportEvaluatePage = schoolLiveAllBean.getTrainingreportevaluatepage();
                                if (trainingReportEvaluatePage.getEvaluatelist() != null && trainingReportEvaluatePage.getEvaluatelist().size() > 0) {
                                    mEvaluateLayout.setVisibility(View.VISIBLE);
                                    mEvaluateHorizontalTagBar.initDataList(trainingReportEvaluatePage.getEvaluatelist());
                                    mEvaluateHorizontalTagBar.setOnHorizontalTagBarClickListener(new HorizontalTagBar.OnHorizontalTagBarClickListener() {
                                        @Override
                                        public void onTagBarClick(int position) {
                                            ReportResultActivity.startActivity(getContext(), trainingReportEvaluatePage.getEvaluatelist().get(position).getId(), "");
                                        }
                                    });
                                } else {
                                    mEvaluateLayout.setVisibility(View.GONE);
                                }

                                if (trainingReportEvaluatePage.getReportlist() != null && trainingReportEvaluatePage.getReportlist().size() > 0) {
                                    mReportLayout.setVisibility(View.VISIBLE);
                                    mReportHorizontalTagBar.initDataList(trainingReportEvaluatePage.getReportlist());
                                    mReportHorizontalTagBar.setOnHorizontalTagBarClickListener(new HorizontalTagBar.OnHorizontalTagBarClickListener() {
                                        @Override
                                        public void onTagBarClick(int position) {
                                            ReportDetailActivity.startActivity(getContext(), trainingReportEvaluatePage.getReportlist().get(position).getId());
                                        }
                                    });
                                } else {
                                    mReportLayout.setVisibility(View.GONE);
                                }

                                if (trainingReportEvaluatePage.getTraininglist() != null && trainingReportEvaluatePage.getTraininglist().size() > 0) {
                                    mPlanLayout.setVisibility(View.VISIBLE);
                                    mPlanHorizontalTagBar.initDataList(trainingReportEvaluatePage.getTraininglist());
                                    mPlanHorizontalTagBar.setOnHorizontalTagBarClickListener(new HorizontalTagBar.OnHorizontalTagBarClickListener() {
                                        @Override
                                        public void onTagBarClick(int position) {
                                            PlanDetailActivity.startActivity(getContext(), trainingReportEvaluatePage.getTraininglist().get(position).getId());
                                        }
                                    });
                                } else {
                                    mPlanLayout.setVisibility(View.GONE);
                                }


                            }

                        } else {
                            mNoDataLayout.setVisibility(View.VISIBLE);
                            mContainerLayout.setVisibility(View.INVISIBLE);
                        }
                    } else {
                        if(response.body().getCode() != 1010){
                            toast(response.body().getMsg());
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<SchoolliveAllResponse> call, Throwable t) {

            }
        });
    }


    @Override
    public void handleUIEvent(Message msg) {

        switch (msg.what) {
            case EventDispatcherEnum.UI_EVENT_DATE_CHANGE:
                String date = (String) msg.obj;
                changeDate(date);
                break;
        }
    }


}
